package ee.ttu.karileet.serviceshop.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ee.ttu.karileet.serviceshop.model.SubjectType;
import ee.ttu.karileet.serviceshop.model.UserAccount;
import ee.ttu.karileet.serviceshop.service.SubjectTypeService;
import ee.ttu.karileet.serviceshop.service.UserAccountService;

@SuppressWarnings("deprecation")
@Service("userDetailsService") 
public class UserDetailsServiceImpl implements UserDetailsService {
	protected final Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private SubjectTypeService subjectTypeService;
	
	@Override
	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException {
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		String username = "";
		String password = "";
		UserAccount account = userAccountService.getUser(arg0);
		logger.info("Auhtenticating: " + arg0);
		if (account != null) {
			username = account.getUsername();
			password = account.getPassw();
			SubjectType type = subjectTypeService.getSubjectTypeById(account.getSubjectTypeFk());
			authorities.add(new GrantedAuthorityImpl(type.getTypeName()));
		} else {
			throw new UsernameNotFoundException("user not found");
		}
	
		User user = new User(username, password, authorities);
		return user;
	}
}
